#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include <opencv2\video\video.hpp>
#include <iostream>
#include "myOpenCVLIB\myheader.h"


using namespace std;  
using namespace cv; 

void showImg(Mat img, char * name){
	namedWindow(name);
	imshow(name,img);
	waitKey();
}

int main(){
	int vmin = 10, vmax = 256, smin = 30;

	Rect selection(100,100,160,100);
	VideoCapture cap = VideoCapture(HIGHWAY);
	Mat frame;
	cap.read(frame);
	Mat roi ;
	roi = frame(selection);


	showImg(frame,"frame");
	showImg(roi,"roi");

	Mat hsvRoi, mask, roiHist,hue;

	cvtColor(frame,hsvRoi,CV_BGR2HSV);
	showImg(hsvRoi,"hsvRoi");


	inRange(hsvRoi, Scalar(0 ,60,32),Scalar(180 ,255,255), mask);
	showImg(mask,"mask");

	float ranges[] = {0,180};
	int hsize = 180;
	const float * pranges = ranges;

	int ch[] = {0,0};

	hue.create(hsvRoi.size(), hsvRoi.depth());
	mixChannels(&hsvRoi,1,&hue,1,ch,1);

	Mat roi2(hue,selection);
		showImg(roi2,"roi2");
	Mat maskroi(mask, selection);
		showImg(maskroi,"maskroi");

	calcHist(&roi2, 1, 0, maskroi, roiHist, 1, &hsize, &pranges);
	//calcHist(&v[0], 1, 0, Mat(), roiHist, 1, &hsize, &pranges);

	showImg(roiHist,"roiHist");

	normalize(roiHist,roiHist,0,255,NORM_MINMAX);
	showImg(roiHist,"normalize");




	TermCriteria tc((TermCriteria::EPS | TermCriteria::COUNT),10,1);

	Mat hsv, dst, show;
	namedWindow("show");


	while(1){

		cap.read(frame);


		if(frame.data){
			cvtColor(frame,hsv,CV_BGR2HSV);
			hue.create(hsv.size(), hsv.depth());
			mixChannels(&hsv,1,&hue,1,ch,1);

			calcBackProject(&hue,1,0,roiHist,dst,&pranges);

			meanShift(dst,selection,tc);

			show = frame.clone();
			rectangle(show, selection,Scalar(255),2);
			imshow("show",show);
			waitKey();
		}
		else{
			break;
		}
	}

	return 0;
}